//
//  Ext.swift
//  WNLockDemo
//
//  Created by peiw on 2018/9/2.
//  Copyright © 2018年 wunu. All rights reserved.
//

import Foundation

public extension UInt32 {
    
    /// 是否为素数
    var isPrime: Bool {
        if self == 2 || self == 3 {
            return true
        }
        // 不在6的两侧一定不是素数
        if self % 6 != 1 && self % 6 != 5 {
            return false
        }
        let tmp = sqrt(Double(self))
        for i in Swift.stride(from: 5, to: tmp, by: 6) {
            if self % UInt32(i) == 0 || self % UInt32(i + 2) == 0 {
                return false
            }
        }
        return true
    }
}

public extension UInt32 {
    static func random(lower: UInt32 = 0, _ upper: UInt32 = UInt32.max) -> UInt32 {
        return lower + arc4random_uniform(upper - lower + 1)
    }
    static func random(_ range: CountableClosedRange<UInt32>) -> UInt32 {
        return random(lower: range.lowerBound, range.upperBound)
    }
    static func randomPrime(length: Double) -> UInt32 {
        // 随机一个8位数
        let lower = pow(10, length - 1)
        let upper = pow(10, length) - 1
        let num = random(UInt32(lower)...UInt32(upper))
        if num.isPrime {
            return num
        }
        // 找随机数最近的素数
        var prime: UInt32 = 2
        var index: UInt32 = 0
        while prime.isPrime {
            index += 1
            if (num + index).isPrime {
                prime = num + index
                break
            }
            if (num - index).isPrime {
                prime = num - index
                break
            }
        }
        return prime
    }
    
}
